
#

import logging
import sys
from urllib import request

from wglmkapplayer.parser import Parser
from wglmkapplayer.mainwriter import MainWriter
from wglmkapplayer.layerwriter import LayerWriter

LOGGER = logging.getLogger("wglmkapplayer")


GL_XML_URL = 'https://raw.githubusercontent.com/KhronosGroup/OpenGL-Registry/main/xml/gl.xml'


# Application
#
class Application :


    # main
    #
    def main (self) :
        self.__setup_logger()
        LOGGER.debug(f"argv: {sys.argv}")
        # [TODO] command line
        mode = None
        basename = None
        xml_file = None
        layer_name = None
        argv = sys.argv[1:]
        argi = 0
        while argi < len(argv) :
            arg = argv[argi]
            if arg == '-u' :
                argi += 1
                self.update_gl_xml(argv[argi])
                sys.exit(0)
            elif arg == '-m' :
                assert not mode, mode
                mode = 'main'
            elif arg == '-l' :
                assert not mode, mode
                mode = 'layer'
                argi += 1
                layer_name = argv[argi]
            elif arg == '-b' :
                argi += 1
                basename = argv[argi]
            else :
                assert not arg.startswith('-'), arg
                assert not xml_file
                xml_file = arg
            argi += 1

        assert mode, "mode required"
        assert xml_file, "xml file required"
        
        parser = Parser(xml_file)
        ast = parser.parse()

        # writer
        if mode == 'main' :
            writer = MainWriter(basename, ast)
        elif mode == 'layer' :
            assert layer_name, "layer name required"
            writer = LayerWriter(basename, layer_name, ast)
            
        writer.write()
        LOGGER.debug("DUMP")
        writer.dump()

    # __setup_logger
    #
    def __setup_logger (self) :
        LOGGER.setLevel(logging.INFO)
        handler = logging.StreamHandler(sys.stderr)
        #formatter = logging.Formatter('%(name)s:%(pathname)s:%(lineno)s:%(levelname)s: %(message)s')
        formatter = logging.Formatter('%(name)s:%(pathname)s:%(lineno)s: %(message)s')
        handler.setFormatter(formatter)
        LOGGER.addHandler(handler)


    # update_gl_xml
    #
    def update_gl_xml (self, dest) :
        LOGGER.info(f"downloading gl.xml from {GL_XML_URL} to {dest}")
        nbytes = 0
        with request.urlopen(GL_XML_URL) as f_in :
            with open(dest, 'w', encoding='utf-8') as f_out :
                for line in f_in :
                    nbytes += len(line)
                    f_out.write(line.decode(encoding='utf-8'))
        LOGGER.info(f"done ({nbytes} bytes read)")
